<?php if (!defined("_ECRIRE_INC_VERSION")) return;

require_once(_DIR_PLUGIN_ECATALOGUE.'classes/class.ArticleOptionModel.php');
require_once(_DIR_PLUGIN_PDK.'classes/models/PdkRubriqueModel.php');

function formulaires_ecatalogue_article_option_charger_dist($id_article) {
    $valeurs = array();

    if ($res = sql_select('id_rubrique', 'spip_articles', 'id_article='.$id_article)) {
        while ($r = sql_fetch($res)) {
            $id_rubrique = $r['id_rubrique'];
        }
    }

    $rubriques = array( $id_rubrique );
    $rubrique_mdl = new PdkRubriqueModel();

    do { // get all parents id
        $rubrique = $rubrique_mdl->select_by_id($id_rubrique);
        $id_rubrique = $rubrique['id_parent'];
        $rubriques[] = $id_rubrique;
    } while ($id_rubrique != '0');

    $groupe_ids = array();
    if ($res = sql_select('id_groupe', 'spip_ecatalogue_rubriques_groupes', 'id_rubrique in ('.implode(',', $rubriques).')')) {
        while ($r = sql_fetch($res)) {
            $groupe_ids[] = $r['id_groupe'];
        }
    }
    $valeurs['groupe_ids'] = $groupe_ids;

    $ao_mdl = new ArticleOptionModel();
    $connections = $ao_mdl->select('id_article='.$id_article);

    foreach ($connections as $connection) {
        $valeurs["options[".$connection['id_option']."]"] = $connection['id_option'];
    }

    return $valeurs;
}


function formulaires_ecatalogue_article_option_verifier_dist($id_article){
    $erreurs = array();
    return $erreurs;
}


function formulaires_ecatalogue_article_option_traiter_dist($id_article) {
    $result = array();

    // Here try/catch is for future...
    try
    {
        $ao_mdl = new ArticleOptionModel();
        // First delete all connections
        $ao_mdl->delete('id_article='.$id_article);

        // Then add all new connections
        $checkboxes = _request('checkboxes');
        if (isset($checkboxes) && $checkboxes && is_array($checkboxes)) {
            foreach ($checkboxes as $id_option=>$id_option) {
                if ($id_option)
                    $ao_mdl->insert(array('id_article'=>$id_article, 'id_option'=>$id_option));
            }
        }

        $selects = _request('selects');
        if (isset($selects) && $selects && is_array($selects)) {
            foreach ($selects as $id_propriete=>$id_option) {
                if ($id_option)
                    $ao_mdl->insert(array('id_article'=>$id_article, 'id_option'=>$id_option));
            }
        }

        $radios = _request('radios');
        if (isset($radios) && $radios && is_array($radios)) {
            foreach ($radios as $id_propriete=>$id_option) {
                if ($id_option)
                    $ao_mdl->insert(array('id_article'=>$id_article, 'id_option'=>$id_option));
            }
        }

        $result['message_ok'] = _T('ecatalogue:form_saved');
    } catch (Exception $e) {
        $result['message_erreur'] = _T('ecatalogue:form_error');
    }

    return $result;
}

?>